package com.probiz.estore.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.common.model.system.AppMenu;
import com.probiz.estore.core.security.ResourceMapping;
import com.probiz.estore.core.security.ResourceMappingProvider;
import com.probiz.estore.system.dao.AppMenuDao;
import com.probiz.estore.system.dao.AppResourceDao;
import com.probiz.estore.webapp.util.RequestContext;

public class ResourceMappingManagerImpl implements ResourceMappingProvider{
	private AppMenuDao appMenuDao = null;
	private AppResourceDao appResourceDao = null;
	protected final transient Log	logger	= LogFactory.getLog(getClass());

	public ResourceMapping[] getResourceMappings() {
		List<AppMenu> allMenus = appMenuDao.findByHql("from AppMenu where url!=null and belongTo=?", RequestContext.getSecurityBelongTo());
		Map<String,ResourceMapping> resMap = new HashMap<String,ResourceMapping>();
		for(int i=0;i<allMenus.size();i++){
			AppMenu menu= allMenus.get(i);
			String[] urlResources = menu.getUrlResources();
			if(null != urlResources){
				for(int j=0; j<urlResources.length; j++){
					String url = urlResources[j];
					ResourceMapping resMapping;
					if(resMap.containsKey(url)){
						resMapping = resMap.get(url);
						resMapping.addRecipients(menu.getAuthorities());
					}else{
						resMapping = new ResourceMapping();
						resMapping.setResourcePath(url);			
						resMapping.setType(menu.getType());
						resMapping.addRecipients(menu.getAuthorities());
						resMap.put(url,resMapping);
					}
					
				}
			}
		}
		
		
		return resMap.values().toArray(new ResourceMapping[0]);
	}
	public void setAppMenuDao(AppMenuDao appMenuDao) {
		this.appMenuDao = appMenuDao;
	}
	public void setAppResourceDao(AppResourceDao appResourceDao) {
		this.appResourceDao = appResourceDao;
	}

}
